package com.taokatao.cardmee.business.carddetail;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.reflect.TypeToken;
import com.taokatao.cardmee.App;
import com.taokatao.cardmee.BaseActivity;
import com.taokatao.cardmee.C;
import com.taokatao.cardmee.R;
import com.taokatao.cardmee.Utils;
import com.taokatao.cardmee.api.ApiManager;
import com.taokatao.cardmee.api.RespWrapper;
import com.taokatao.cardmee.api.SubscriberAdapter;
import com.taokatao.cardmee.api.model.CardFDMyCourseInfo;
import com.taokatao.cardmee.api.model.CardFDSignInfo;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 商家分店对应的界面
 */
public class CardFDSignActivity extends BaseActivity implements View.OnClickListener {
    @BindView(R.id.b_submit) Button bSubmit;
    @BindView(R.id.l_course_container) LinearLayout lCourseContainer;
    List<CardFDMyCourseInfo> mCourseInfoList;
    List<View> vCourseInfoList = new ArrayList<>();
    List<ImageView> vCourseInfoState = new ArrayList<>();

    final LinearLayout.LayoutParams lpLine = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, (int) (App.i().d1() * 0.5));
    /**
     * 当前所选
     */
    private int currIdx = -1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        isSupportTouchBack = false;
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_card_fd_sign);
        ButterKnife.bind(this);

        String data = getIntent().getStringExtra("extra_course_list");
        Utils.logd("CardFDSignActivity data:" + data);
        List<CardFDMyCourseInfo> courseInfoList = App.i().getGson().fromJson(data, new TypeToken<List<CardFDMyCourseInfo>>() {
        }.getType());
        prepareCourseList(courseInfoList);
    }

    private void addLine(ViewGroup parent) {
        View vLine = new View(this);
        vLine.setBackgroundColor(0xFFE9E9E9);
        vLine.setLayoutParams(lpLine);
        parent.addView(vLine);
    }

    private void prepareCourseList(List<CardFDMyCourseInfo> courseInfoList) {
        if (courseInfoList != null && courseInfoList.size() > 0) {
            mCourseInfoList = courseInfoList;

            vCourseInfoState.clear();
            vCourseInfoList.clear();
            lCourseContainer.removeAllViewsInLayout();

            addLine(lCourseContainer);
            for (int i = 0; i < courseInfoList.size(); i++) {
                final CardFDMyCourseInfo info = courseInfoList.get(i);
                View item = LayoutInflater.from(this).inflate(R.layout.recycler_card_fd_sign, null);
                lCourseContainer.addView(item);

                TextView tCourseName = (TextView) item.findViewById(R.id.t_course_name);
                tCourseName.setText(info.courseName);
                TextView tCourseCount = (TextView) item.findViewById(R.id.t_course_count);
                tCourseCount.setText(info.coursePerimeter + "课时");
                TextView tTeacherName = (TextView) item.findViewById(R.id.t_teacher_name);
                tTeacherName.setText(info.teacherName);
                TextView tTime = (TextView) item.findViewById(R.id.t_time);
                tTime.setText(formatTime(info.classTime));

                ImageView iLogo = (ImageView) item.findViewById(R.id.i_logo);
                Glide.with(this).load(info.coursePic).placeholder(R.mipmap.card_fd_course_default).
                        bitmapTransform(App.i().getRoundedCornersTransformation()).into(iLogo);
                ImageView iState = (ImageView) item.findViewById(R.id.i_state);
                iState.setImageResource(R.mipmap.card_fd_sign_normal);

                vCourseInfoState.add(iState);
                vCourseInfoList.add(item);
                addLine(lCourseContainer);

                item.setOnClickListener(this);
            }


            vCourseInfoList.get(0).performClick();
        }
    }

    SimpleDateFormat parser = new SimpleDateFormat("yyyyMMddHHmmss");
    SimpleDateFormat formatter = new SimpleDateFormat("HH:mm");

    private String formatTime(long timestamp) {
        String sTimestamp = String.valueOf(timestamp);
        if (sTimestamp.length() != 14) return "";
        String result = "";
        try {
            Date date = parser.parse(sTimestamp);
            result = formatter.format(date);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            return result;
        }
    }

    @Override
    @OnClick({R.id.b_submit})
    public void onClick(View v) {
        if (v == bSubmit) {
            CardFDMyCourseInfo cci = mCourseInfoList.get(currIdx);
            requestUserActiveSignConfirm(cci);
        } else if (vCourseInfoList.contains(v)) {
            currIdx = vCourseInfoList.indexOf(v);

            bSubmit.setText("确认签到");
            bSubmit.setEnabled(true);
            bSubmit.setTextColor(0xFFFFFFFF);
            bSubmit.setBackgroundResource(R.drawable.selector_btn_red);

            for (int i = 0; i < vCourseInfoState.size(); i++) {
                ImageView iState = vCourseInfoState.get(i);
                iState.setImageResource(i == currIdx ? R.mipmap.card_fd_sign_selected : R.mipmap.card_fd_sign_normal);
            }
        }
    }

    /**
     * 签到请求
     */
    private void requestUserActiveSignConfirm(CardFDMyCourseInfo cci) {
        ApiManager.i().userActiveSignConfirm(this, App.i().getCurrUser().getUuid(), cci.cardId, cci.sid,
                cci.courseInfoId, cci.courseId, new SubscriberAdapter<RespWrapper<CardFDSignInfo>>() {
                    @Override
                    public void onNext(RespWrapper<CardFDSignInfo> o) {
                        super.onNext(o);
                        if (o.code == C.http.RESULT_CODE_SUCCESS) {
                            Intent intent = new Intent(CardFDSignActivity.this, CardFDSignCompleteActivity.class);
                            intent.putExtra("extra_course_sign_info", o.decode(CardFDSignInfo.class));
                            startActivity(intent);
                            finish();
                        }
                    }
                }.showProgress(this));
    }
}
